package com.mzy.NetworkProgram.networkinterfacebasic.networkimagess;

import com.alibaba.fastjson.JSON;
import com.mzy.NetworkProgram.networkinterfacebasic.data.Constants;
import com.mzy.NetworkProgram.networkinterfacebasic.data.DevMeter;
import com.mzy.NetworkProgram.networkinterfacebasic.data.NetworkInfo;
import com.mzy.NetworkProgram.networkinterfacebasic.utils.JavaCollectUtils;
import lombok.extern.slf4j.Slf4j;
import org.testng.annotations.Test;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/7/6 15:10
 * @Version 1.0
 */
@Slf4j
public class MonitorTest {
    private static Map<String, NetworkInfo> networkInfoMap;
    public static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    public static ScheduledFuture<?> starterFuture = null;


    /**
     * 没毛病，可作为范例
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("每二秒监控一次");

        if (starterFuture == null) {
            ScheduledFuture<?> scheduledFuture = executorService.scheduleAtFixedRate(() -> {
                DevMeter devMeter = new DevMeter();
                networkInfoMap = OshiCollectUtils.getNetworkInfoMap(networkInfoMap);
                devMeter.setCpuInfo(OshiCollectUtils.getCpuInfo());
                devMeter.setFileSystemInfo(OshiCollectUtils.getFileSystemInfo());
                devMeter.setMemInfo(JavaCollectUtils.getMemInfo());
                devMeter.setNetworkInfo(networkInfoMap);
                // 将对象转换为json字符串
                String jsonString = JSON.toJSONString(devMeter,true);
                System.out.println(jsonString);

            }, 0, Constants.meterPushInterval, TimeUnit.MILLISECONDS);

            starterFuture = scheduledFuture;
        } else {
            log.info("启动性能监控：{}", "失败");
        }
    }


    public static void DevMeterClose() {
        if (starterFuture != null) {
            starterFuture.cancel(true);
            starterFuture = null;
        }
    }
}
